package com.ppp.poi.config;

import com.ppp.poi.common.interceptor.AuthInterceptor;
import com.ppp.poi.common.interceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author Wu Jin
 * @create 2019-08-08
 */
@Slf4j
@Configuration
public class AppMvcConfiguration extends WebMvcConfigurationSupport {

  @Bean
  HandlerInterceptor authInterceptor() {
    return new AuthInterceptor();
  }

  @Bean
  HandlerInterceptor loginInterceptor() {
    return new LoginInterceptor();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(loginInterceptor()).addPathPatterns("/login");
    registry.addInterceptor(authInterceptor())
        .excludePathPatterns("/login", "/sso/**", "/ping", "/test").addPathPatterns("/**");
    super.addInterceptors(registry);
    log.info("登录认证过滤器加载完毕");
  }

  private CorsConfiguration corsConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setMaxAge(3600L);
    return corsConfiguration;
  }

  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfig());
    return new CorsFilter(source);
  }
}
